import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

import 'package:get/get.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:sainbainu/common/utils/loading.dart';
import 'package:sainbainu/common/utils/permission.dart';

import 'package:photo_view/photo_view_gallery.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

/// 图片预览+保存
class PhotoViewSaver extends StatefulWidget {
  final List images;
  final int index;
  final bool enableDownload;

  const PhotoViewSaver({
    super.key,
    required this.images,
    this.index = 0,
    this.enableDownload = true,
  });

  @override
  State<PhotoViewSaver> createState() => _PhotoViewSaverState();
}

class _PhotoViewSaverState extends State<PhotoViewSaver> {
  int currentIndex = 0;
  int imagesLength = 0;
  late PageController pageController;

  @override
  void initState() {
    super.initState();
    currentIndex = widget.index;
    pageController = PageController(initialPage: currentIndex);
    imagesLength = widget.images.length;
  }

  /// 检查保存权限
  Future<void> _handleCheckPermi(void Function() success) async {
    PermissionStatus status = await Permission.photos.status;
    // 尚未请求权限或临时拒绝过
    if (!status.isGranted && !status.isLimited) {
      await PermissionUtil.reqPermissions(
        permissions: [Permission.photos],
        displayRationale: true,
        onPermissionRequestResult: (results) {
          PermissionStatus status = results[Permission.photos]!;
          if (status.isGranted || status.isLimited) {
            success();
          }
        },
      );
    } else {
      success();
    }
  }

  /// 保存相册
  _handleDownload(int currentIndex) {
    _handleCheckPermi(() async {
      try {
        LoadingUtil.showLoading(text: '保存中');
        final response = await Dio().get(
          widget.images[currentIndex],
          options: Options(responseType: ResponseType.bytes),
        );
        final result = await ImageGallerySaver.saveImage(
          Uint8List.fromList(response.data),
        );
        if (result['isSuccess']) {
          LoadingUtil.showSuccess('已保存至相册');
        } else {
          LoadingUtil.showError('保存失败');
        }
      } catch (e) {
        LoadingUtil.dismiss();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          Positioned.fill(
            child: PhotoViewGallery.builder(
              scrollPhysics: const BouncingScrollPhysics(),
              itemCount: imagesLength,
              builder: (BuildContext context, int index) {
                if (widget.images[index] is AssetEntity) {
                  return PhotoViewGalleryPageOptions(
                    imageProvider:
                        AssetEntityImageProvider(widget.images[index]),
                    tightMode: true,
                    onTapUp: (context, details, controllerValue) {
                      Get.back();
                    },
                  );
                }
                return PhotoViewGalleryPageOptions(
                  imageProvider: NetworkImage(widget.images[index]),
                  tightMode: true,
                  onTapUp: (context, details, controllerValue) {
                    Get.back();
                  },
                );
              },
              wantKeepAlive: true,
              backgroundDecoration: const BoxDecoration(color: Colors.black),
              loadingBuilder: (BuildContext context, ImageChunkEvent? ice) {
                return const Center(
                  child: SizedBox(
                    width: 40,
                    height: 40,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      valueColor: AlwaysStoppedAnimation(Colors.white),
                    ),
                  ),
                );
              },
              pageController: pageController,
              onPageChanged: (int index) {
                setState(() {
                  currentIndex = index;
                });
              },
            ),
          ),
          Positioned(
            top: MediaQuery.of(context).padding.top,
            right: 10,
            child: IconButton(
              onPressed: () {
                Get.back();
              },
              icon: const Icon(Icons.close),
              iconSize: 30,
              color: Colors.white,
            ),
          ),
          Positioned(
            bottom: MediaQuery.of(context).padding.bottom,
            left: 10,
            right: 10,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '${currentIndex + 1}/$imagesLength',
                  style: const TextStyle(color: Colors.white, fontSize: 16),
                ),
                if (widget.enableDownload)
                  IconButton(
                    onPressed: () => _handleDownload(currentIndex),
                    icon: const Icon(Icons.download),
                    iconSize: 30,
                    color: Colors.white,
                    enableFeedback: true,
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
